package com.icode.web.validator;

import com.icode.core.dto.user.LoginDTO;
import com.icode.core.model.user.Customer;
import com.icode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created with IntelliJ IDEA.
 * User: sunk
 * Date: 14-12-30
 * Time: 下午4:27
 * To change this template use File | Settings | File Templates.
 */
@Component
public class LoginFormValidator implements Validator {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return LoginDTO.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        LoginDTO loginDTO = (LoginDTO) target;
        String phoneNum = loginDTO.getUserName();
        isAccountExist(errors, loginDTO, phoneNum);
    }

    private void isAccountExist(Errors errors, LoginDTO loginDTO, String phoneNum) {
        Customer customer = userService.findByPhoneNum(phoneNum);
        if (customer == null) {
            errors.rejectValue("phoneNum", null, "账号未注册!");
        } else {
            isSuccessFulForLogin(errors, loginDTO);
        }
    }

    private void isSuccessFulForLogin(Errors errors, LoginDTO loginDTO) {
        boolean isSuccess = userService.login(loginDTO);
        if (!isSuccess) {
            errors.rejectValue("password", null, "账号和密码不匹配!");
        }
    }
}
